//
// Created by sgyt on 2020/5/18.
// select-io多路复用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
    int fd;
    int res,i;

    struct timeval timeval;

    char buf[100];
    char ch;

    fd_set readfds;

    while(1)
    {
        FD_ZERO(&readfds);
        FD_SET(STDIN_FILENO,&readfds);

        //设置请求的阻塞的时间
        timeval.tv_sec = 5;
        timeval.tv_usec = 0;

        //开启多路复用io
        res = select(STDIN_FILENO+1,&readfds,NULL,NULL,&timeval);

        if(res < 0)
        {
            perror("select is error\n");
        }else if(res == 0){
            printf("等待超时\n");
            continue;
        }else{
            if(FD_ISSET(STDIN_FILENO,&readfds))
            {
                memset(buf,0x00, sizeof(buf));
                i = read(STDIN_FILENO,buf,100);
                if(i<0)
                {
                    perror("read is error\n");
                }else{
                    printf("buf:[%s],size:[%d]\n",buf,i);
                }
            }
        }

    }
    return 0;
}

